"use client"

import { useState, useEffect } from "react"
import { usePlayer } from "@/contexts/player-context"
import { Button } from "@/components/ui/button"
import { Heart, X, Shuffle, ListMusic, Repeat1Icon as RepeatOne } from "lucide-react"
import { mockSongs } from "@/lib/mock-data"

type PlayMode = "sequential" | "random" | "loop"

export default function PlaylistViewPage() {
  const { state, toggleFavorite, removeSong, clearQueue, toggleShuffle, toggleLoop, addToQueue } = usePlayer()

  const [playMode, setPlayMode] = useState<PlayMode>("sequential")

  // Initialize queue with mock data if empty
  useEffect(() => {
    if (state.queue.length === 0) {
      mockSongs.forEach((song) => addToQueue(song))
    }
  }, [addToQueue, state.queue.length])

  const handlePlayModeChange = () => {
    const modes: PlayMode[] = ["sequential", "random", "loop"]
    const currentIndex = modes.indexOf(playMode)
    const nextMode = modes[(currentIndex + 1) % modes.length]
    setPlayMode(nextMode)

    switch (nextMode) {
      case "random":
        toggleShuffle()
        break
      case "loop":
        toggleLoop()
        break
      default:
        // Reset both shuffle and loop
        if (state.isShuffle) toggleShuffle()
        if (state.isLoop) toggleLoop()
    }

    window.history.back()
  }

  const getPlayModeIcon = () => {
    switch (playMode) {
      case "random":
        return <Shuffle className="w-4 h-4" />
      case "loop":
        return <RepeatOne className="w-4 h-4" />
      default:
        return <ListMusic className="w-4 h-4" />
    }
  }

  const formatTime = (seconds: number) => {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
  }

  const handleClearQueue = () => {
    clearQueue()
    window.history.back()
  }

  return (
    <div className="flex flex-col h-screen bg-background">
      <div className="flex-1 flex flex-col">
        <div className="flex justify-between items-center p-4 text-sm text-muted-foreground border-b">
          <div className="flex items-center gap-2">
            <Button
              variant="ghost"
              size="sm"
              className="text-muted-foreground hover:text-primary"
              onClick={handlePlayModeChange}
            >
              {getPlayModeIcon()}
              <span className="ml-2">
                {playMode === "sequential" ? "顺序播放" : playMode === "random" ? "随机播放" : "单曲循环"}(
                {state.queue.length})
              </span>
            </Button>
          </div>
          <Button
            variant="ghost"
            size="sm"
            className="text-muted-foreground hover:text-destructive"
            onClick={handleClearQueue}
          >
            清空
          </Button>
        </div>

        <div className="flex-1 overflow-y-auto">
          {state.queue.map((song, index) => (
            <div
              key={song.id}
              className={`flex items-center p-4 border-b ${state.currentSong?.id === song.id ? "bg-primary/5" : ""}`}
            >
              <div className="flex-1 min-w-0">
                <div className="font-medium truncate">
                  {song.title}
                  {state.currentSong?.id === song.id && <span className="text-primary ml-2">(播放中)</span>}
                </div>
                <div className="text-sm text-muted-foreground truncate">{song.artists}</div>
              </div>
              <div className="text-sm text-muted-foreground mr-4">{formatTime(song.duration)}</div>
              <Button
                variant="ghost"
                size="icon"
                className="text-muted-foreground hover:text-primary"
                onClick={() => toggleFavorite(song)}
              >
                <Heart className={`h-4 w-4 ${song.isLiked ? "fill-primary text-primary" : ""}`} />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="text-muted-foreground hover:text-destructive"
                onClick={() => {
                  removeSong(index)
                  if (state.queue.length === 1) {
                    window.history.back()
                  }
                }}
              >
                <X className="h-4 w-4" />
              </Button>
            </div>
          ))}
        </div>
      </div>

      <Button variant="ghost" className="m-4" onClick={() => window.history.back()}>
        关闭
      </Button>
    </div>
  )
}

